package com.yincheng.oes.business.schedule;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Timer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author yangsiyong
 * @version 1.0
 * @description: 定时任务管理类
 * @date 2022/3/13 10:22 PM
 */
@Component
public class ScheduleTaskManager {
    /**
     * 日志
     */
    private static final Logger logger = LogManager.getLogger(ScheduleTaskManager.class);

    private final static BlockingQueue<AbstractScheduleTask> tasks = new ArrayBlockingQueue<>(1024);

    private static final ScheduleTaskManager INSTANCE = new ScheduleTaskManager();

    private ScheduleTaskManager() {

    }

    public static ScheduleTaskManager getInstance() {
        return INSTANCE;
    }

    public boolean offer(AbstractScheduleTask task) {
        return tasks.offer(task);
    }

    @PostConstruct
    public void init() {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(2 * 60 * 1000L);
            } catch (InterruptedException e) {
                logger.error("when suspend schedule task error", e);
            }
            logger.info("start execute schedule task");
            while (true) {
                try {
                    // take 防止cpu被占用
                    AbstractScheduleTask scheduleTask = tasks.take();
                    Timer timer = new Timer();
                    timer.schedule(scheduleTask, scheduleTask.getStartTime(), scheduleTask.getPeriod());
                } catch (InterruptedException e) {
                    logger.error("when execute schedule task error", e);
                }
            }
        });
        thread.start();
    }
}
